<script setup>
import {ref, onMounted, computed} from 'vue'
import { useUserInfoStore } from '@/stores/userInfo'
import {ElMessage, ElMessageBox} from 'element-plus'
import router from '@/router'
import {getCartListByUserId, updateCartQuantity, deleteCartItem, submitOrder, updateUserLevelAndBenefits, getUserLevelByConsumption  } from "@/api/user";
import { getUserAddressList } from '@/api/user' // 假设你已封装好接口

const userInfoStore = useUserInfoStore()
const cartList = ref([])

const fetchCartList = async () => {
  const userId = userInfoStore.userInfo?.id
  if (!userId) {
    ElMessage.warning('尚未登录，请先登录')
    return router.push('/login')
  }
  const res = await getCartListByUserId(userId)
  if (res.status === true && res.data) {
    cartList.value = res.data
  } else {
    ElMessage.error('加载购物车失败')
  }
}

onMounted(() => {
  fetchCartList()
})

const backShopping = () => {
  router.push('/shopping')
}

const userDiscountRate = computed(() => {
  return userInfoStore.userInfo?.discountRate ?? 1
})

const pointsMultiplier = computed(() => {
  return userInfoStore.userInfo?.pointsMultiplier ?? 0
})

const isPointsMall = computed(() => {
  return cartList.value.some(item => item.pointsMall === true)
})

const getFinalPrice = (product) => {
  const basePrice = product.price
  const productDiscountedPrice = product.productDiscountRate < 1 ? basePrice * product.productDiscountRate : basePrice
  const memberDiscountedPrice = productDiscountedPrice * userDiscountRate.value
  return memberDiscountedPrice.toFixed(2)
}

const getPointsReturn = (product) => {
  const finalPrice = parseFloat(getFinalPrice(product))
  return (finalPrice * 0.1 * pointsMultiplier.value).toFixed(1)
}

const getCartTotal = computed(() => {
  return cartList.value
      .filter(item => !item.pointsMall)
      .reduce((sum, item) => sum + parseFloat(getFinalPrice(item)) * item.quantity, 0)
      .toFixed(2)
})

const getPointsTotal = computed(() => {
  return cartList.value
      .filter(item => item.pointsMall)
      .reduce((sum, item) => sum + item.pointsPrice * item.quantity, 0)
})

const handleQuantityChange = async (item, newQuantity) => {
  // 先检查库存是否为0
  if (item.inventory === 0) {
    try {
      await ElMessageBox.confirm('商品已经售罄，是否移出购物车', '确认移出', {
        type: 'warning'
      })
      await deleteCartItem(item.id)
      ElMessage.success('已移除该商品')
      fetchCartList()
    } catch {
      // 用户取消操作，恢复原数量
      item.quantity = 0
      return
    }
    return
  }

  // 正常处理数量变更
  if (newQuantity === 0) {
    try {
      await ElMessageBox.confirm('数量为0，将删除该商品，是否继续？', '确认删除', {
        type: 'warning'
      })
      await deleteCartItem(item.id)
      ElMessage.success('已删除该商品')
      fetchCartList()
    } catch {
      // 用户取消操作，恢复数量为1
      item.quantity = 1
    }
  } else {
    // 检查新数量是否超过库存
    if (newQuantity > item.inventory) {
      ElMessage.warning(`库存不足，最多可购买 ${item.inventory} 件`)
      item.quantity = item.inventory
      return
    }

    const res = await updateCartQuantity(item.id, newQuantity)
    if (res.status === true) {
      ElMessage.success('数量更新成功')
      item.quantity = newQuantity
    } else {
      ElMessage.error('更新失败')
      // 恢复原数量
      item.quantity = Math.min(item.quantity, item.inventory)
    }
  }
}

const handleDeleteItem = async (item) => {
  try {
    await ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
      type: 'warning'
    })
    await deleteCartItem(item.id)
    ElMessage.success('删除成功')
    fetchCartList()
  } catch {
    // 用户取消操作
  }
}

const getCartPointsReturnedTotal = computed(() => {
  return cartList.value
      .filter(item => !item.pointsMall && pointsMultiplier.value > 0)
      .reduce((sum, item) => {
        const returnPoints = parseFloat(getPointsReturn(item)) * item.quantity
        return sum + returnPoints
      }, 0)
      .toFixed(1)
})

const showCheckoutDialog = ref(false)
const userBalance = computed(() => userInfoStore.userInfo?.balance ?? 0)

// 差值计算
const totalPrice = computed(() => {
  return parseFloat(getCartTotal.value)
})

const totalPointsPrice = computed(() => {
  return getPointsTotal.value
})

const balanceDifference = computed(() => {
  return (userBalance.value - totalPrice.value).toFixed(2)
})

const isBalanceEnough = computed(() => {
  return userBalance.value >= totalPrice.value
})

const openCheckoutDialog = async () => {
  if (cartList.value.length === 0) {
    ElMessage.warning('购物车为空，无法结算')
    return
  }
  await fetchUserAddresses()
  showCheckoutDialog.value = true
}

const handleConfirmCheckout = async () => {
  const cartItems = cartList.value.map(item => ({
    productId: item.productId,
    quantity: item.quantity,
    finalPrice: parseFloat(getFinalPrice(item)),
    pointsMall: item.pointsMall,
    pointsPrice: item.pointsPrice,
    cartItemId: item.id
  }))

  const payload = {
    userId: userInfoStore.userInfo.id,
    addressId: selectedAddressId.value,
    cartItems
  }

  try {
    const oldLevelId = userInfoStore.userInfo.levelId

    const res = await submitOrder(payload)

    if (res.status === true || res.code === 200) {
      ElMessage.success(res.message || '订单提交成功')
      showCheckoutDialog.value = false
      await fetchCartList() // 清空购物车

      // 🔄 重新拉取用户信息，获取最新 totalConsumption
      await userInfoStore.fetchUserInfo()
      const newTotal = userInfoStore.userInfo.totalConsumption
      const newLevelInfo = getUserLevelByConsumption(newTotal)
      const newLevelId = newLevelInfo.levelId

      // ⬆️ 触发后端等级更新（不带 totalConsumption）
      await updateUserLevelAndBenefits({
        userId: userInfoStore.userInfo.id,
        ...newLevelInfo
      })

      // 再次拉取确认等级已更新（可选）
      await userInfoStore.fetchUserInfo()

      if (newLevelId > oldLevelId) {
        let message = `恭喜您升级为等级 ${newLevelId}，享受 ${(newLevelInfo.discountRate * 100).toFixed(0)}% 折扣，${newLevelInfo.pointsMultiplier} 倍积分返还！`;

        // 根据新等级添加特殊权益提示
        if (newLevelId === 5) {
          message += "\n\n您可以享受：无条件退款特权！";
        } else if (newLevelId === 4) {
          message += "\n\n您可以享受：1000元以下商品急速退款！";
        }

        // 一次性升级到5级时只显示5级信息
        if (oldLevelId < 4 && newLevelId === 5) {
          message = `恭喜您升级为等级 5，享受 ${(newLevelInfo.discountRate * 100).toFixed(0)}% 折扣，${newLevelInfo.pointsMultiplier} 倍积分返还！\n\n您可以享受：无条件退款特权！`;
        }

        ElMessageBox.alert(
            message,
            '等级升级提示',
            { type: 'success' }
        )
      }
    } else {
      ElMessage.error(res.message || '订单提交失败')
    }
  } catch (error) {
    ElMessage.error('网络错误或服务器异常')
  }
}



const handleCancelCheckout = () => {
  showCheckoutDialog.value = false
}

const userPoints = computed(() => userInfoStore.userInfo?.points ?? 0)

const pointsDifference = computed(() => {
  return userPoints.value - totalPointsPrice.value
})

const isPointsEnough = computed(() => {
  return userPoints.value >= totalPointsPrice.value
})

const addressList = ref([])
const selectedAddressId = ref(null)

const fetchUserAddresses = async () => {
  const userId = userInfoStore.userInfo?.id
  if (!userId) return
  try {
    const res = await getUserAddressList(userId)
    if (res.status === true && res.data) {
      addressList.value = res.data
      // 默认选中默认地址
      selectedAddressId.value = res.data.find(addr => addr.default)?.id ?? res.data[0]?.id
    }
  } catch (e) {
    ElMessage.error('加载地址失败')
  }
}

onMounted(() => {
  userInfoStore.fetchUserInfo()
})

</script>

<template>
  <div class="cart-container">
    <el-card shadow="hover" class="header-card">
      <div class="cart-header">
        <div class="header-left">
          <h1 class="cart-title">我的购物车</h1>
        </div>
        <el-icon class="back-icon" @click="backShopping"><ArrowLeft /></el-icon>
        <el-button type="primary"  @click="backShopping" class="back-btn">
          继续购物
        </el-button>
      </div>
    </el-card>
    <div v-if="cartList.length" class="cart-content">
      <el-card shadow="hover" class="cart-card">
        <el-table :data="cartList" stripe style="width: 100%">
          <el-table-column prop="name" label="商品名称" width="220">
            <template #default="scope">
              <div class="product-name">
                <el-image
                    :src="scope.row.mainImage || 'https://via.placeholder.com/60'"
                    fit="cover"
                    class="product-image"
                />
                <span>{{ scope.row.name }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="productColor" label="颜色" width="100" align="center" />
          <el-table-column prop="productSize" label="尺码" width="100" align="center" />

          <el-table-column label="单价" width="180" align="center">
            <template #default="scope">
              <div class="price-container">
                <template v-if="scope.row.pointsMall">
                  <div class="points-price">{{ scope.row.pointsPrice }} 积分</div>
                </template>
                <template v-else>
                  <div v-if="scope.row.productDiscountRate < 1" class="discount-price">
                    <span class="original-price">{{ scope.row.price }} 元</span>
                    <span class="current-price">{{ (scope.row.price * scope.row.productDiscountRate).toFixed(2) }} 元</span>
                  </div>
                  <div v-else class="normal-price">
                    {{ scope.row.price }} 元
                  </div>
                  <div v-if="userDiscountRate < 1" class="member-price">
                    会员价: {{ getFinalPrice(scope.row) }} 元
                  </div>
                </template>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="数量" align="center">
            <template #default="scope">
              <div v-if="scope.row.inventory === 0" class="out-of-stock">
                已售罄
              </div>
              <el-input-number
                  v-model="scope.row.quantity"
                  :min="0"
                  :max="scope.row.inventory"
                  :disabled="scope.row.inventory === 0"
                  @change="(val) => handleQuantityChange(scope.row, val)"
                  size="small"
                  controls-position="right"
              />
            </template>
          </el-table-column>

          <el-table-column label="返还积分" width="120" align="center">
            <template #default="scope">
              <template v-if="!scope.row.pointsMall && pointsMultiplier > 0">
                <span class="points-return">{{ getPointsReturn(scope.row) }}</span>
              </template>
              <template v-else>
                <span class="no-points">-</span>
              </template>
            </template>
          </el-table-column>

          <el-table-column label="小计" width="150" align="center">
            <template #default="scope">
              <template v-if="scope.row.pointsMall">
                <span class="points-total">{{ scope.row.pointsPrice * scope.row.quantity }} 积分</span>
              </template>
              <template v-else>
                <span class="price-total">￥{{ (getFinalPrice(scope.row) * scope.row.quantity).toFixed(2) }}</span>
              </template>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="100" align="center">
            <template #default="scope">
              <el-button
                  type="danger"
                  size="small"
                  @click="handleDeleteItem(scope.row)"
                  plain
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <el-card shadow="never" class="summary-card">
        <div class="summary-content">
          <div v-if="getCartTotal > 0" class="summary-item">
            <span class="summary-label">商品总金额：</span>
            <span class="summary-value">￥{{ getCartTotal }}</span>
          </div>
          <div v-if="getPointsTotal > 0" class="summary-item">
            <span class="summary-label">积分商品总计：</span>
            <span class="summary-value">{{ getPointsTotal }} 积分</span>
          </div>
          <div v-if="getCartPointsReturnedTotal > 0" class="summary-item">
            <span class="summary-label">预计返还积分：</span>
            <span class="summary-value">{{ getCartPointsReturnedTotal }} 积分</span>
          </div>
        </div>

        <div class="checkout-actions">
          <el-button type="primary" size="large" class="checkout-btn" @click="openCheckoutDialog">
            去结算
          </el-button>
        </div>
      </el-card>
    </div>

    <el-empty v-else description="购物车空空如也~" class="empty-cart">
      <el-button type="primary" @click="backShopping">去逛逛</el-button>
    </el-empty>
  </div>
  <el-dialog
      v-model="showCheckoutDialog"
      title="结算确认"
      width="400px"
      :close-on-click-modal="false"UU
  >
    <div class="checkout-dialog-content">
      <p>商品总价：<strong>￥{{ totalPrice }}</strong></p>
      <p v-if="totalPointsPrice > 0">积分商品总价：<strong>{{ totalPointsPrice }} 积分</strong></p>
      <p>您的余额：<strong>￥{{ userBalance }}</strong></p>
      <p v-if="totalPointsPrice > 0">您的积分：<strong>{{ userPoints }}</strong></p>

      <p>
        <span v-if="isBalanceEnough" style="color: green;">您的余额充足</span>
        <span v-else style="color: red;">您的余额不足，差 {{ Math.abs(balanceDifference) }} 元</span>
      </p>

      <p v-if="totalPointsPrice > 0">
        <span v-if="isPointsEnough" style="color: green;">您的积分充足</span>
        <span v-else style="color: red;">您的积分不足，差 {{ Math.abs(pointsDifference) }} 积分</span>
      </p>
    </div>

    <p>请选择收货地址：</p>
    <el-radio-group v-model="selectedAddressId" class="address-radio-group">
      <el-radio
          v-for="addr in addressList"
          :key="addr.id"
          :label="addr.id"
          style="display: block; margin-bottom: 8px"
      >
        {{ addr.province }}{{ addr.city }}{{ addr.district }}{{ addr.detail }}
      </el-radio>
    </el-radio-group>

    <template #footer>
    <span class="dialog-footer">
      <el-button @click="handleCancelCheckout">取消</el-button>
      <el-button type="primary" @click="handleConfirmCheckout">提交</el-button>
    </span>
    </template>
  </el-dialog>

</template>

<style scoped lang="scss">
.cart-container {
  max-width: 1200px;
  height: 120px;
  margin: 0 auto;
  padding: 20px;
}

.cart-header {
  position: relative;
  z-index: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 120px; // ✅ 明确指定高度，便于垂直居中对比
}

.cart-title {
  color: deeppink;
  font-size: 24px;
  font-weight: bold;
  margin: 0;
  line-height: 1; // ✅ 避免默认行高拉高高度
}

.back-btn {
  margin-left: 10px;
  height: 40px;      // ✅ 确保按钮高度不会撑开行高
  line-height: 40px; // ✅ 和高度一致，确保文字垂直居中
  padding: 0 16px;
}

.back-icon {
  font-size: 20px;
  margin-right: 10px;
  cursor: pointer;
  height: 40px;
  display: flex;
  align-items: center;
}


.cart-content {
  margin-top: 20px;
}

.cart-card {
  /* 背景图设置 */
  background-image: url('@/assets/IMG_20250630_192130.png');
  background-size: cover; /* 或 contain 根据需求调整 */
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed; /* 可选，固定背景 */
  background-color: rgba(255, 255, 255, 1); /* 背景色带透明度 */

  /* 确保表格内容可读 */
  :deep(.el-table) {
    background-color: transparent; /* 表格透明 */

    th, tr {
      background-color: rgba(255, 255, 255, 0.5); /* 表头行半透明 */
    }

    td {
      background-color: rgba(255, 255, 255, 0.3); /* 单元格更透明 */
    }
  }

  /* 调整卡片内部样式 */
  :deep(.el-card__body) {
    padding: 0; /* 移除默认padding */
    background-color: transparent;
  }
}

.summary-card {
  background-image: url('@/assets/IMG_20250630_185554.png'); /* 替换为你的图片路径 */
  background-size: cover;
  background-position: center;
  opacity: 1; /* 控制透明度，避免遮挡文字 */
  border-radius: 8px;
  background-color: #f8f8f8;
}

.summary-content {
  padding: 20px;
  text-align: right;
}

.summary-item {
  margin-bottom: 12px;
  font-size: 16px;

  &:last-child {
    margin-bottom: 0;
  }
}

.summary-label {
  color: #666;
}

.summary-value {
  font-weight: bold;
  color: #e4393c;
  margin-left: 10px;
}

.checkout-actions {
  display: flex;
  justify-content: flex-end;
  padding: 20px;
  border-top: 1px solid #eee;
}

.checkout-btn {
  width: 180px;
  height: 48px;
  font-size: 16px;
}

.product-name {
  display: flex;
  align-items: center;
}

.product-image {
  width: 60px;
  height: 60px;
  margin-right: 12px;
  border-radius: 4px;
}

.price-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.original-price {
  text-decoration: line-through;
  color: #999;
  font-size: 12px;
}

.current-price {
  color: #e4393c;
  font-weight: bold;
  font-size: 14px;
}

.member-price {
  color: #409eff;
  font-size: 12px;
  margin-top: 4px;
}

.points-price {
  color: #ff9900;
  font-weight: bold;
}

.points-return {
  color: #ff9900;
  font-weight: bold;
}

.no-points {
  color: #999;
}

.points-total {
  color: #ff9900;
  font-weight: bold;
}

.price-total {
  color: #e4393c;
  font-weight: bold;
}

.empty-cart {
  margin-top: 60px;
  padding: 40px 0;
  background-color: #fff;
  border-radius: 8px;
}

.discount-price {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.normal-price {
  font-weight: bold;
}
.header-card {
  position: relative;
  overflow: hidden; /* 避免图片超出 */
}

.header-card::before {
  content: '';
  position: absolute;
  inset: 0;
  background-image: url('@/assets/IMG_20250630_185554.png'); /* 替换为你的图片路径 */
  background-size: cover;
  background-position: center;
  opacity: 1; /* 控制透明度，避免遮挡文字 */
  z-index: 0;
}

.cart-header {
  position: relative;
  z-index: 1; /* 确保内容在背景图上层 */
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
}

.cart-title {
  font-size: 24px;
  font-weight: bold;
}

.back-icon {
  cursor: pointer;
  font-size: 20px;
  margin-right: 10px;
}

.back-btn {
  margin-left: 10px;
}

.out-of-stock {
  color: #f56c6c;
  font-size: 12px;
  padding: 5px;
  background-color: #fef0f0;
  border-radius: 4px;
}

</style>
